package io.shdxhl.simplerpc.code.utils;

import io.netty.channel.Channel;
import io.shdxhl.simplerpc.code.netty.ChannelMapping;
import io.shdxhl.simplerpc.code.netty.RpcRequestPromise;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RequestUtil {
    private static Map<String, RpcRequestPromise> requestMap = new ConcurrentHashMap<>();


    /**
     * 添加异步回调Promise
     * @param requestId
     * @param requestPromise
     */
    public static void addRequest(String requestId, RpcRequestPromise requestPromise) {
        requestMap.put(requestId, requestPromise);
    }

    /**
     * 获取异步回调Promise
     * @param requestId
     * @return
     */
    public static RpcRequestPromise getRequest(String requestId) {
        return requestMap.get(requestId);
    }

    /**
     * 移除异步回调
     * @param requestId
     */
    public static void removeRequest(String requestId) {
        requestMap.remove(requestId);
    }


    //Channel 映射集
    private static Map<String, ChannelMapping> channelMap = new ConcurrentHashMap<>();

    /**
     * 获取指定的ChannelMapping
     * @param channelId
     * @return
     */
    public static ChannelMapping getChannel(String channelId) {
        return channelMap.get(channelId);
    }
    public static Channel getChannel(String ip, int port) {
        String key = ip + ":" + port;
        ChannelMapping channelMapping = channelMap.get(key);
        if(Objects.nonNull(channelMapping)){
            return channelMapping.getChannel();
        }
        return null;
    }

    /**
     * 添加指定的Channel 对象
     * @param channelId
     * @param channelMapping
     */
    public static void addChannel(String channelId, ChannelMapping channelMapping) {
        channelMap.put(channelId, channelMapping);
    }

    /**
     * 检查当前channel释放存在
     * @param ip
     * @param port
     * @return
     */
    public static boolean hasChannel(String ip, int port) {
        return channelMap.containsKey(ip + ":" + port);
    }

    /**
     * 移除指定的channel对象
     * @param channelId
     */
    public static void removeChannel(String channelId) {
        channelMap.remove(channelId);
    }



}
